package com.dw.receiver.strategy.impl;

import com.dw.common.bean.NetNode;
import com.dw.common.bean.ResourceBean;
import com.dw.common.service.KVService;
import com.dw.common.service.impl.KVServiceImpl;
import com.dw.receiver.ReceiverConfiguration;
import com.dw.receiver.strategy.NodeSelection;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NodeSelectionImpl implements NodeSelection {
    private final KVService kvService;
    @Setter
    private ResourceBean resource;

    public NodeSelectionImpl(ResourceBean resource) {
        kvService = new KVServiceImpl();
        this.resource = resource;
    }

    @Override
    public List<NetNode> getNetNodeList() {
        List<String> nodeStrings = kvService.getWithPrefix(resource.getPrefix());
        int maxNodeCount = Math.toIntExact(resource.getLength() / ReceiverConfiguration.MIN_SPLIT_SIZE);
        List<NetNode> nodeList = new ArrayList<>();
        Collections.shuffle(nodeStrings);
        for (String string : nodeStrings) {
            String endPoint = kvService.get(string);
            NetNode node = NetNode.stringToNetNode(endPoint);
            if (node != null && node.getTaskCounts() < ReceiverConfiguration.TASK_COUNT_THRESHOLD) {
                nodeList.add(node);
            }
            if (nodeList.size() > maxNodeCount) {
                break;
            }
        }
        return nodeList;
    }
}
